/*
 * @Author: qsy
 * @Date: 2024-01-19 17:10:13
 * @LastEditors: qsy
 * @LastEditTime: 2024-08-30 17:21:25
 * @Description: 请填写简介
 */
#include "ads1115.h"
#include "esp_log.h"

#define ADS1115_I2C_PORT I2C_NUM_1
#define ADS1115_ADDRESS 0x48

void read_all_channels(ads1115_t *ads) {
    ads1115_mux_t mux_settings[] = {
        ADS1115_MUX_0_GND,
        ADS1115_MUX_1_GND,
        ADS1115_MUX_2_GND,
        ADS1115_MUX_3_GND
    };


    for (int i = 0; i < 4; i++) {
        ads1115_set_mux(ads, mux_settings[i]);
        vTaskDelay(pdMS_TO_TICKS(1)); // 等待转换完成，最小延迟
        int16_t raw_value = ads1115_get_raw(ads); // raw_value 为 16 位有符号整数
        double voltage = ads1115_get_voltage(ads);
        ESP_LOGI("ADS1115", "Channel %d: Raw Value = %d, Voltage = %.4f V", i, raw_value, voltage);
    }
}

void app_main(void) {
    // 初始化 I2C 总线
    i2c_config_t conf = {
        .mode = I2C_MODE_MASTER,
        .sda_io_num = 48,
        .scl_io_num = 47,
        .sda_pullup_en = GPIO_PULLUP_ENABLE,
        .scl_pullup_en = GPIO_PULLUP_ENABLE,
        .master.clk_speed = 400000 // 使用400kHz的I2C时钟速度
    };
    i2c_param_config(ADS1115_I2C_PORT, &conf);
    i2c_driver_install(ADS1115_I2C_PORT, conf.mode, 0, 0, 0);

    // 配置 ADS1115
    ads1115_t ads = ads1115_config(ADS1115_I2C_PORT, ADS1115_ADDRESS);
    ads1115_set_pga(&ads, ADS1115_FSR_4_096); // 设置最小增益，最大增益范围
    ads1115_set_mode(&ads, ADS1115_MODE_CONTINUOUS); // 设置为连续转换模式
    ads1115_set_sps(&ads, ADS1115_SPS_860); // 设置最大采样率

    while (1) {
        // 读取所有通道
        read_all_channels(&ads);
        vTaskDelay(pdMS_TO_TICKS(100)); // 每秒读取一次
    }

    // 关闭 I2C 总线
    i2c_driver_delete(ADS1115_I2C_PORT);
}
